﻿using Digitalmes.Infrastructure.Brokers.LedGuide;
using ThingsEdge.Contracts;

namespace Digitalmes.Infrastructure.Scada.Handlers;

/// <summary>
/// LedGuide 接收到数据后处理。
/// </summary>
public sealed class LedGuideRecivedHandler : IReciveMessageHandler
{
    /// <summary>
    /// 前缀
    /// </summary>
    public const string PrefixKey = "PLC_Guide";

    // 地址1
    const string PLC_Guide_Index_Prefix = "PLC_Guide_Index";
    const string PLC_Guide_Torque_Prefix = "PLC_Guide_Torque";
    const string PLC_Guide_Angle_Prefix = "PLC_Guide_Angle";
    const string PLC_Guide_Result_Prefix = "PLC_Guide_Result";

    // 地址2
    const string PLC_Guide_SN = "PLC_Guide_SN";
    const string PLC_Guide_Profile = "PLC_Guide_Profile";

    private readonly LedGuideBroker _ledGuideBroker;
    private readonly ILogger _logger;

    public LedGuideRecivedHandler(LedGuideBroker ledGuideBroker, ILogger<LedGuideRecivedHandler> logger)
    {
        _ledGuideBroker = ledGuideBroker;
        _logger = logger;
    }

    public async Task ReciveAsync(RequestMessage requestMessage, CancellationToken cancellationToken)
    {
        try
        {
            var self = requestMessage.Self();

            if (self.TagName.StartsWith(PLC_Guide_Index_Prefix))
            {
                // 索引格式，如 "PLC_Guide_Index_1"、"PLC_Guide_Index_A"，末尾的下划线代表分组，没有分组即为 "PLC_Guide_Index"。
                string group = "";
                if (self.TagName.Length > PLC_Guide_Index_Prefix.Length)
                {
                    group = self.TagName[(PLC_Guide_Index_Prefix.Length + 1)..];
                }

                int index = self.GetInt();

                // 过程数据格式与索引格式相同
                string torqueTag = string.IsNullOrEmpty(group) ? PLC_Guide_Torque_Prefix : $"{PLC_Guide_Torque_Prefix}_{group}";
                double torque = requestMessage.GetData(torqueTag)?.GetReal() ?? 0;

                string angleTag = string.IsNullOrEmpty(group) ? PLC_Guide_Angle_Prefix : $"{PLC_Guide_Angle_Prefix}_{group}";
                double angle = requestMessage.GetData(angleTag)?.GetReal() ?? 0;

                string resultTag = string.IsNullOrEmpty(group) ? PLC_Guide_Result_Prefix : $"{PLC_Guide_Result_Prefix}_{group}";
                int result = requestMessage.GetData(resultTag)?.GetInt() ?? 1;

                var model = new LedGuideTightenModel()
                {
                    Index = index,
                    Group = group,
                    Torque = Math.Round(torque, 3),
                    Angle = Math.Round(angle, 3),
                    Result = result == 1,
                };
                _logger.LogInformation("拧紧数据: {Model}", model.ToJson());

                await _ledGuideBroker.QueueAsync(model, cancellationToken);
            }
            else if (self.TagName == PLC_Guide_SN)
            {
                var sn = self.GetString();
                if (string.IsNullOrEmpty(sn))
                {
                    return;
                }

                var profile = requestMessage.GetData(PLC_Guide_Profile)?.GetString();
                var model = new LedGuideSnModel()
                {
                    SN = sn,
                    ProfileName = profile,
                };
                _logger.LogInformation("SN 数据: {Model}", model.ToJson());

                await _ledGuideBroker.QueueAsync(model, cancellationToken);
            }

        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "LedGuide 接收数据处理异常");
        }
    }
}
